import { ProForm } from '@ant-design/pro-components';
import { useEffect, useState } from 'react';
import UserDetailDrawer from './components/UserDetailDrawer';

interface Props {
  open: boolean;
  data: API.UserDetailInfo;
  onClose: () => void;
}

// 数据格式化函数
function formatFormDataToUserDetailInfo(formData: any): API.UserDetailInfo {
  const result: API.UserDetailInfo = {
    name: formData.name || '',
    phones: [],
  };

  // 提取所有手机相关的字段
  const phoneFields: { [key: string]: any } = {};

  Object.keys(formData).forEach((key) => {
    if (key.startsWith('phone_')) {
      phoneFields[key] = formData[key];
    }
  });

  // 按索引分组手机数据
  const phoneGroups: { [index: string]: any } = {};

  Object.keys(phoneFields).forEach((key) => {
    const match = key.match(/phone_(\d+)_(\w+)/);
    if (match) {
      const [, index, field] = match;
      if (!phoneGroups[index]) {
        phoneGroups[index] = {};
      }
      phoneGroups[index][field] = phoneFields[key];
    }
  });

  // 转换为 Phone 对象数组
  result.phones = Object.keys(phoneGroups)
    .sort((a, b) => parseInt(a) - parseInt(b)) // 按索引排序
    .map((index) => {
      const phoneData = phoneGroups[index];
      return {
        phone: phoneData.model || '', // model 字段对应 phone 属性
        ref: {
          brand: phoneData.brand || '',
          price:
            typeof phoneData.price === 'number'
              ? phoneData.price
              : phoneData.price
              ? parseFloat(phoneData.price) || 0
              : 0,
          color: phoneData.color || '',
        },
      } as API.Phone;
    })
    .filter(
      (phone) =>
        phone.phone || phone.ref.brand || phone.ref.price || phone.ref.color,
    ); // 过滤空数据

  return result;
}

export default ({ open, data, onClose }: Props) => {
  const [form] = ProForm.useForm();
  const [currentData, setCurrentData] = useState<API.UserDetailInfo>(data);
  const onOk = async (values: any) => {
    console.log('子组件表单提交值:', values);
    const formattedData = formatFormDataToUserDetailInfo(values);
    console.log('formattedData:', formattedData);

    console.log('格式化后的数据:', JSON.stringify(formattedData, null, 2));
  };
  useEffect(() => {
    setCurrentData(data);
  }, [data]);

  useEffect(() => {
    if (!open) {
      form.resetFields();
      // console.log('抽屉关闭，重置表单');
      return;
    }

    if (currentData) {
      // console.log('接收到数据:', currentData);
      // console.log('phones数据:', currentData.phones);

      // 使用 form.setFieldsValue 设置初始值
      const formValues: any = {
        name: currentData?.name || '',
      };

      // 设置手机信息的初始值
      if (currentData?.phones && currentData?.phones.length > 0) {
        currentData?.phones.forEach((phone, index) => {
          formValues[`phone_${index}_model`] = phone.phone || '';
          formValues[`phone_${index}_brand`] = phone.ref?.brand || '';
          formValues[`phone_${index}_price`] = phone.ref?.price || '';
          formValues[`phone_${index}_color`] = phone.ref?.color || '';
        });
      }
      // console.log('formValues:', formValues);

      form.setFieldsValue(formValues);
      // console.log('设置表单初始值:', formValues);
    }
  }, [currentData, open, form]);

  const handleDataChange = (newData: API.UserDetailInfo) => {
    setCurrentData(newData);
    // console.log('数据已更新:', newData);
  };

  // console.log('phones数据结构:', JSON.stringify(currentData?.phones, null, 2));
  return (
    <>
      <UserDetailDrawer
        title="编辑"
        data={currentData}
        readonly={false}
        form={form}
        onClose={onClose}
        open={open}
        onDataChange={handleDataChange}
        onOk={onOk}
        onFieldsChange={() => {
          // 字段变化处理逻辑
        }}
      />
    </>
  );
};
